const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const reqlib = require('app-root-path').require
const btbAs = reqlib('/app/common/btb')
const commonDataCreate = require('./utils/commonDataCreate')

const BtbIndex = Proxy.BtbIndex

// 获取合约账户财务信息
module.exports = async function () {
  // 找出币
  let btbRes = await BtbIndex.findWidthField({
    status: 1,
    hy_status: 1
  }, {
    countResultInfo: 0,
    monthEmaInfo: 0,
    weekEmaInfo: 0,
    dayEmaInfo: 0,
    hour4EmaInfo: 0,
    hourEmaInfo: 0,
    minute15EmaInfo: 0
  }, {
    sort: '-proportion'
  })
  // 总占比
  const btbIndexConfig = {
    proportionAll: 0,
    balance: {},
    btbList: []
  }
  // 查K线
  for (let i = 0; i < btbRes.length; i++) {
    const btbItem = btbRes[i]
    if (btbItem.proportion) {
      btbIndexConfig.proportionAll += btbItem.proportion
      try {
        // 小时K线
        let dayKlineRes = await webDataUtil.getBIBTKlines({
          name: `${btbItem.code}`,
          interval: '1w'
        })
        let asInfo = await btbAs.getItemInfoList(dayKlineRes)
        // 近的在右
        let asList = [...asInfo]
        // 近的在左
        asInfo.reverse()
        asInfo.forEach((v, index) => {
          commonDataCreate.asInfoExtend(asInfo, v, index)
        })
        btbIndexConfig.btbList.push({
          ...commonDataCreate.btbListItemExtend(btbItem, asInfo, asList),
          // 近的在右边
          emInfoList: asList.map((em) => {
            return commonDataCreate.emInfoListItemExtend(em)
          })
        })
        dayKlineRes = null
        asInfo = null
        asList = null
      } catch (e) {
        console.error(`星期分析报错[${btbItem.code}]：${e.toString()}`)
      }
    }
  }
  if (btbIndexConfig.btbList.length === 0) {
    return false
  }
  btbIndexConfig.btbList.forEach(async (v) => {
    const em = v.asInfo[0] || {}
    await BtbIndex.update({
      code: v.code
    }, {
      weekEmaInfo: {
        ...commonDataCreate.indexUpdateItemExtend(v, em)
      }
    })
  })
  return btbIndexConfig
}
